<template>
  <div class="app-container">
        <el-row :gutter="20">
            <el-row>
              <el-col :span="24">
                <el-form :model="params" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" style="float: right">
                  <el-form-item label="时间">
                    <el-date-picker
                      v-model="dateRange"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <line-chart :title="'水质pH'" :chartId="'id1'"  :chartWidth="'300px'" :chartHeight="'300px'" :label="this.label" :labelValue="this.labelValue[0]"/>
              </el-col>
              <el-col :span="8">
                <line-chart :title="'溶解氧'" :chartId="'id2'"  :chartWidth="'300px'" :chartHeight="'300px'" :label="this.label" :labelValue="this.labelValue[1]"/>
              </el-col>
              <el-col :span="8">
                <line-chart :title="'水温'" :chartId="'id3'"  :chartWidth="'300px'" :chartHeight="'300px'" :label="this.label" :labelValue="this.labelValue[2]"/>
              </el-col>
            </el-row>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>
    <el-table :data="this.waterQualityData.rows" :height="300" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="水质PH(pH)" align="center" prop="ph"/>
      <el-table-column label="水温(℃)" align="center" prop="temperature"/>
      <el-table-column label="导电性(mg/L)" align="center" prop="ec"/>
      <el-table-column label="溶解氧((mg/L)" align="center" prop="dissolvedOxygen"/>
      <el-table-column label="氨氮(ppm)" align="center" prop="ammoniaNitrogen"/>
      <el-table-column label="时间" align="center" prop="time">
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :current-page="this.params.page"
      :page-size="this.params.pageSize"
      :total="1000"
      @current-change="handleCurrentPageChange"
      style="float: right">
    </el-pagination>

  </div>
</template>

<script>
  import {listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus} from "@/api/system/user";
  import {getToken} from "@/utils/auth";
  import {treeselect} from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import lineChart from "@/components/LineChart"
  import {getWaterQuality} from "@/api/agriculture/water";

  export default {
    name: "User",
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: {Treeselect, lineChart},
    props: {
      device: {
        type: Object,
        required: true,
      }
    },
    data() {
      return {
        // 水质数据
        waterQualityData: [],
        // 折线数据
        label: [],
        labelValue: [],

        // 查询参数
        params: {
          page: 1,
          pageSize: 10,
          deviceId: "21075797",
          startTime: null,
          endTime: null,
        },

      };
    },
    async mounted() {
      // 休眠 1000 毫秒（1秒）执行查询，因为插槽异步传递属性机制，deviceId会为空
      setTimeout(() => {
        //获取水质数据
         this.fetchWaterData();
      }, 1000);
    },

    methods: {
      // 分页查询
      handleCurrentPageChange(newPage) {
        this.params.page = newPage
        this.fetchWaterData()
        this.getLinchartData()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.params.page = 1
        this.params.startTime = this.changeTime(this.dateRange[0])
        this.params.endTime = this.changeTime(this.dateRange[1])
        this.fetchWaterData()
        this.getLinchartData()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = ''
        this.params.startTime = null
        this.params.endTime = null
        this.fetchWaterData()
        this.getLinchartData()
      },
      // 折线图数据
      getLinchartData() {
        this.label = this.waterQualityData.rows.map(entry => entry.time)
        this.labelValue[0] = this.waterQualityData.rows.map(entry => entry.ph)
        this.labelValue[1] = this.waterQualityData.rows.map(entry => entry.dissolvedOxygen)
        this.labelValue[2] = this.waterQualityData.rows.map(entry => entry.temperature)
      },

      // 获取水质数据
      async fetchWaterData() {
        console.log(this.device.deviceId);
        this.params.deviceId = this.device.deviceId
        let response = await getWaterQuality(this.params)
        // 获取返回数据的最近时间
        const backendTimeStr = response.rows[0].time;
        // 将返回的时间字符串转换为Date对象
        const backendTime = new Date(backendTimeStr);
        // 获取当前时间的Date对象
        const currentTime = new Date();
        // 计算两个时间点之间的时间差，单位为毫秒
        const timeDifference = currentTime - backendTime;
        // 20分钟的时间戳（以毫秒为单位）
        const twentyMinutes = 20 * 60 * 1000;
        // 判断时间差是否超过20分钟
        if (timeDifference > twentyMinutes) {
          console.log("时间超过20分钟");
          this.params.deviceId = "21075798";
          response = await getWaterQuality(this.params)
        } else {
          console.log("时间未超过20分钟");
        }
        this.waterQualityData = response;
        this.getLinchartData()
      },

      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        const idMapping = {
          1: {showData: true, empty: false},
          2: {showData: false, empty: true},
          3: {showData: false, empty: true},
          4: {showData: false, empty: true},
          5: {showData: false, empty: true},
        };
        const selectedData = idMapping[data.id] || {showData: false, empty: true};
        this.showData = selectedData.showData;
        this.empty = selectedData.empty;
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleResetPwd":
            this.handleResetPwd(row);
            break;
          case "handleAuthRole":
            this.handleAuthRole(row);
            break;
          default:
            break;
        }
      },
      // 化时间日期
      changeTime(originalDateString) {
        const originalDate = new Date(Date.parse(originalDateString));
        const year = originalDate.getFullYear();
        const month = String(originalDate.getMonth() + 1).padStart(2, '0');
        const day = String(originalDate.getDate()).padStart(2, '0');
        const hours = String(originalDate.getHours()).padStart(2, '0');
        const minutes = String(originalDate.getMinutes()).padStart(2, '0');
        const seconds = String(originalDate.getSeconds()).padStart(2, '0');
        const formattedDateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        return formattedDateString;
      },

    },

  };
</script>
